package com.yzyz.management.web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yzyz.bean.hotel.HotelBean;
import com.yzyz.bean.hotel.HotelPictureBean;
import com.yzyz.bean.scenic.PictureBean;
import com.yzyz.service.IHotelPictureService;
import com.yzyz.service.IHotelService;
import com.yzyz.service.PictureService;
import com.yzyz.utils.CommonHandle;
import com.yzyz.utils.Star;
import com.yzyz.utils.ValidateUtils;
import com.yzyz.utils.error.ErrorBean;
import com.yzyz.utils.error.Error;
import com.yzyz.utils.json.management.JSONHotelPictureM;
import com.yzyz.utils.json.management.JSONPictureM;
import com.yzyz.utils.json.processor.StarProcessor;

/**
 * 管理员管理酒店信息
 * @author david.sun
 * @date 2010-7-11
 */
public class HotelController extends MultiActionController {
	
	private IHotelService hotelService;
	
	private IHotelPictureService hotelPictureService;
	
	private PictureService pictureService;
	
	public void setPictureService(PictureService pictureService) {
		this.pictureService = pictureService;
	}

	public void setHotelService(IHotelService hotelService) {
		this.hotelService = hotelService;
	}

	public void setHotelPictureService(IHotelPictureService hotelPictureService) {
		this.hotelPictureService = hotelPictureService;
	}
	
	@SuppressWarnings("unchecked")
	public void paginate(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int start = 0;
		int limit = 15;
		String hotelName = request.getParameter("hotelName");
		String scenicName = request.getParameter("scenicName");
		if(!ValidateUtils.isNull(request.getParameter("start"))) {
			start = Integer.valueOf(request.getParameter("start"));
		}
		List<HotelBean> list = null;
		if(ValidateUtils.isNull(hotelName) && ValidateUtils.isNull(scenicName)) {
			list = (List<HotelBean>) this.hotelService.paginate(start, limit);
		} else {
			list = this.hotelService.paginate(start, limit, hotelName, scenicName);
		}
			
		if(list == null){
			list = new ArrayList<HotelBean>();
		}
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Star.class, new StarProcessor());
		config.setExcludes(new String[]{"pictures"});
		JSONArray arr = JSONArray.fromObject(list, config);
		StringBuffer sb = new StringBuffer();
		sb.append("{\"sum\":").append("\""+this.hotelService.getCount()+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
	}
	
	/**
	 * 添加酒店
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void addHotel(HttpServletRequest request, HttpServletResponse response) throws IOException{
		HotelBean hotel = new HotelBean();
		hotel.setAddress(request.getParameter("address"));
		hotel.setDescription(request.getParameter("description"));
		hotel.setName(request.getParameter("name"));
		hotel.setStatus(Star.getInstance(Integer.valueOf(request.getParameter("star"))));
		hotel.setPrice(request.getParameter("price"));
		int result = this.validateNewHotel(hotel);
		if(result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
		}
		this.hotelService.add(hotel);
		int id = hotel.getId();
		this.writeToClient(response, ErrorBean.getInstance(result, id).toJson());
		
	}
	
	/**
	 * 删除酒店
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void deleteHotel(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		int result = this.hotelService.delete(Integer.valueOf(request.getParameter("hotelId")));
		if(result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
			return;
		}
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	/**
	 * 更新酒店信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void updateHotel(HttpServletRequest request, HttpServletResponse response) throws IOException{
		HotelBean hotel = (HotelBean)this.hotelService.find(Integer.valueOf(request.getParameter("hotelId")));
		if(hotel == null) {
			this.writeToClient(response, ErrorBean.getInstance(Error.CAN_NOT_FIND_OBJECT).toJson());
			return;
		}
		hotel.setId(Integer.valueOf(request.getParameter("hotelId")));
		hotel.setAddress(request.getParameter("address"));
		hotel.setDescription(request.getParameter("description"));
		hotel.setName(request.getParameter("name"));
		hotel.setStatus(Star.getInstance(Integer.valueOf(request.getParameter("star"))));
		hotel.setPrice(request.getParameter("price"));
		int result = this.validateNewHotel(hotel);
		if(result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
		}
		result = this.hotelService.update(hotel);
		if(result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
		} else {
			this.writeToClient(response, ErrorBean.getSuccessMsg());
		}

	}
	
	/**
	 * 禁止某个酒店，则此酒店就不能被显示
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void disable(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int hotelId = Integer.valueOf(request.getParameter("hotelId"));
		boolean available = false;
		int result = this.hotelService.updateAvailable(hotelId, available);
		if(result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
		} else {
			this.writeToClient(response, ErrorBean.getSuccessMsg());
		}
		
	}
	
	/**
	 * 激活某个酒店
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void enable(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int hotelId = Integer.valueOf(request.getParameter("hotelId"));
		boolean available = true;
		int result = this.hotelService.updateAvailable(hotelId, available);
		if(result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
		} else {
			this.writeToClient(response, ErrorBean.getSuccessMsg());
		}
	}
	
	/**
	 * 获取某张图片
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void getPicture(HttpServletRequest request, HttpServletResponse response) throws IOException{
		HotelPictureBean p = (HotelPictureBean)this.hotelPictureService.find(Integer.valueOf(request.getParameter("pictureId")));
		byte [] image = this.pictureService.resize(this.pictureService.bytes2Image(p.getContents()), 120, 90, "jpg");
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "attachment; filename=" + p.getName());//设置图片的名字
		response.setContentLength(image.length);
		OutputStream out = response.getOutputStream();
		out.write(image);
		out.flush();
		out.close();
	}
	
	/**
	 * 获取图片的内容用来编辑
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getImageForEdit(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String imageId = request.getParameter("pictureId");
		if(ValidateUtils.isNull(imageId)){
			return;
		}
		String hotelId = request.getParameter("hotelId");
		if(ValidateUtils.isNull(hotelId)) {
			return;
		}
		PictureBean p = (HotelPictureBean)this.hotelPictureService.find(Integer.valueOf(imageId));
		if(p == null) {
			return;
		}
		
		byte[] image = this.pictureService.resize(this.pictureService.bytes2Image(p.getContents()), 300, 215, "jpg");
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "attachment; filename=" + p.getName());//设置图片的名字
		response.setContentLength(image.length);
		OutputStream out = response.getOutputStream();
		out.write(image);
		out.flush();
		out.close();
	}
	
	/**
	 * 列出某个酒店的所有图片
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void viewPictures(HttpServletRequest request, HttpServletResponse response) throws IOException{
		List<HotelPictureBean> pictures = this.hotelPictureService.listAll(Integer.valueOf(request.getParameter("hotelId")));
		List<JSONHotelPictureM> list = new ArrayList<JSONHotelPictureM>();
		String url = CommonHandle.getUrl(request);
		if(pictures != null) {
			for(HotelPictureBean picture: pictures) {
				JSONHotelPictureM p = new JSONHotelPictureM(picture, url);
				list.add(p);
			}
		}
		JSONArray js = JSONArray.fromObject(list, JSONPictureM.getConfig());
		StringBuilder sb = new StringBuilder();
		sb.append("{\"images\":").append(js.toString()).append("}");
		this.writeToClient(response, sb.toString());
	}
	
	/**
	 * 更新图片，但是不能更新图片内容
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void updatePicture(HttpServletRequest request, HttpServletResponse response) throws IOException{
		HotelPictureBean picture = (HotelPictureBean)this.hotelPictureService.find(Integer.valueOf(request.getParameter("pictureId")));
		if(picture == null) {
			this.writeToClient(response, ErrorBean.getInstance(Error.CAN_NOT_FIND_OBJECT).toJson());
			return;
		}
		picture.setName(request.getParameter("name"));
		picture.setDescription(request.getParameter("description"));
		this.hotelPictureService.update(picture);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	
	/**
	 * 删除图片
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void deletePicture(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.hotelPictureService.delete(Integer.valueOf(request.getParameter("pictureId")));
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	/**
	 * 添加图片
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public ModelAndView addPicture(HttpServletRequest request, HttpServletResponse response) throws IOException{
		if(!(request instanceof MultipartHttpServletRequest)) {
			ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
			mv.addObject("errorMsg","您上传的图片为空");
			return mv;
		}
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
		MultipartFile file = multipartRequest.getFile("image");
		String strOwnerId = request.getParameter("hotelId");
		if(ValidateUtils.isNull(strOwnerId)) {
			ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
			mv.addObject("errorMsg","您上传的图片为空");
			return mv;
		}
		
		InputStream in = file.getInputStream();
		long size = file.getSize();
		byte [] image = new byte[(int)size];
		int left = image.length;
		int read = 0;
		while(read != -1 && left > 0) {
			read = in.read(image, image.length - left, left);
			left = image.length - read;
			System.out.println("read:" + ((float)(image.length-left)/(float)image.length));
		}
		BufferedImage bi = this.pictureService.bytes2Image(image);
		image = this.pictureService.resize(bi, 600, 450, "jpeg");
		HotelPictureBean p = new HotelPictureBean();
		p.setName(request.getParameter("name"));
		p.setDescription(request.getParameter("description"));
		p.setHotelId(Integer.valueOf(request.getParameter("hotelId")));
		p.setContents(image);
		this.hotelPictureService.add(p);
		
		ModelAndView mv = new ModelAndView("/Admin/Hotel/Picture/picture.jsp?hotelId=" + request.getParameter("hotelId"));
		return mv;
	}
	
	/**
	 * 保存酒店-景区的关联关系
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void saveScenic(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int hotelId = Integer.valueOf(request.getParameter("hotelId"));
		int scenicId = Integer.valueOf(request.getParameter("scenicId"));
		int result = this.hotelService.saveScenic(hotelId, scenicId);
		if( result != Error.SUCCESS) {
			this.writeToClient(response, ErrorBean.getInstance(result).toJson());
		} else {
			this.writeToClient(response, ErrorBean.getSuccessMsg());
		}
	}
	
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
	
	/**
	 * 验证新添加的酒店数据的完整性
	 * @param hotel
	 * @return
	 */
	private int validateNewHotel(HotelBean hotel){
		
		if(ValidateUtils.isNull(hotel.getName())) {
			return Error.HOTEL_NAME_REQUIRED;
		}
		if(ValidateUtils.isNull(hotel.getAddress())) {
			return Error.HOTEL_ADDRESS_REQUIRED;
		}
		if(ValidateUtils.isNull(hotel.getDescription())) {
			return Error.HOTEL_DESCRIPTION_REQURIED;
		}
		if(hotel.getDescription().length() > 50000) {
			return Error.HOTEL_DESCRIPTION_TOO_LONG;
		}
		return Error.SUCCESS;
		
	}

	
}
